const tbody = document.querySelector('tbody')
const province = document.querySelector('select[name=province]')
const city = document.querySelector('select[name=city]')
const county = document.querySelector('select[name=county]')
const form = document.querySelector('.add-form')
// 定义一个全局变量id  表示修改的id
// let id
// 查询数据
async function getData() {
    const res = await axios({
        url: '/student/list',
    })
    const { data } = res.data
    const html = data.map((i) => {
        const { id, name, age, sex, group, phone, salary, truesalary, province, city, county } = i
        return `
    <tr>
        <th scope="row">${id}</th>
        <td>${name}</td>
        <td>${age}</td>
        <td>${sex}</td>
        <td>${group}</td>
        <td>${phone}</td>
        <td>${salary}</td>
        <td>${truesalary}</td>
        <td>${province + city + county}</td>
        <td>
          <button type="button" class="btn btn-primary btn-sm" data-id=${id}>修改</button>
          <button type="button" class="btn btn-danger btn-sm">删除</button>
        </td>
      </tr>
    `
    }).join('')
    tbody.innerHTML = html
}

// 数据初始化省市区
async function getSelectData(url, params, text, target) {
    const res = await axios({
        url,
        params
    })
    const html = res.data.reduce((j, i) => {
        return j + `
        <option value='${i}'>${i}</option>
        `
    }, `<option value=''>===${text}===</option>`)
    target.innerHTML = html
}

async function initSlelect() {
    getSelectData('/geo/province', {}, '省', province)
}
getData()
initSlelect()

province.addEventListener('change', async function () {
    getSelectData('/geo/city', { pname: province.value }, '市', city)
    county.innerHTML = county.firstChild.outerHTML
})
city.addEventListener('change', async function () {
    getSelectData('/geo/county', { pname: province.value, cname: city.value }, '区', county)
})

// 添加
form.addEventListener('submit', async (e) => {
    e.preventDefault()
    const data = serialize(form, { hash: true, empty: true })
    for (const key in data) {
        if (!data[key]) {
            toastr.error('错了', '宝贝')
            return
        }
    }


    // 判断当前是新增还是编辑
    const formTitle = document.querySelector('#addModalLabel').innerText
    let res
    if (formTitle === '添加新学员') {
        // 新增不需要带上的id 所以删除即可
        delete data.id
        // 调用接口 完成新增
        res = await axios({ url: "/student/add", method: "post", data })

    } else if (formTitle === '修改牛马学员') {
        // 修改要多一个id
        // data.id = id
        res = await axios({ url: "/student/update", method: "put", data })
    }
    if (res.data.code === 0) {
        toastr.success(res.data.message, '恭喜')
        $('#addModal').modal('hide')
        getData()
        form.reset()
        city.innerHTML = city.firstChild.outerHTML
        county.innerHTML = county.firstChild.outerHTML
    }
})
// 修改
// 给编辑按钮绑定事件  （事件委托）
tbody.addEventListener('click', async function (e) {
    const target = e.target
    if (target.classList.contains('btn-primary')) {
        $('#addModal').modal('show')
        document.querySelector('#addModalLabel').innerText = '修改牛马学员'
        // 获取身上的id
        let id = target.dataset.id
        // console.log(target.dataset.id);
        // 获取id对应的学员数据
        const res = await axios({
            url: '/student/one',
            params: {
                id
            }
        })
        const obj = res.data.data
        for (const key in obj) {
            const formEle = document.querySelector(`[name=${key}]`)
            if (formEle && key !== 'sex') {
                formEle.value = obj[key]
            }
        }
        document.querySelector(`[name=sex][value=${obj.sex}]`).checked = true
    }

})


